#include "StdAfx.h"
#include "SoundFXdx.h"

namespace directx{

SoundFXdx::SoundFXdx(void)
{
}

SoundFXdx::~SoundFXdx(void)
{
}

SoundFXdx::SoundFXdx(LPDIRECTSOUNDBUFFER8 _SB, LPDIRECTSOUND8 _lpds,int nV)
{
	m_lpSB = _SB;
	lpds = _lpds;
	numberOfVoices = nV;
}

void SoundFXdx::destroy(){
	
	std::map<int,LPDIRECTSOUNDBUFFER8>::iterator it;

	for (it = voices.begin(); it != voices.end(); it++) {
		LPDIRECTSOUNDBUFFER8 tempBuffer = it->second;
		tempBuffer->Release();
	}

	voices.clear();
	lpds->Release();
	m_lpSB = NULL;
}

bool SoundFXdx::play(){
	HRESULT hr;
	if(m_lpSB){
		
		LPDIRECTSOUNDBUFFER8 tempBuf = NULL;
		
		for(int i=1; i <= numberOfVoices; i++){
			tempBuf = voices[i];
			if(!tempBuf){
				LPDIRECTSOUNDBUFFER copyBuf;
				
				hr = lpds->DuplicateSoundBuffer(m_lpSB, &copyBuf);
				
				if (SUCCEEDED(hr)) 
				{ 
					hr = copyBuf->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*) &tempBuf);
					copyBuf->Release();
				}
				
				voices[i] = tempBuf;			
			}
			DWORD bufStat=0;
			tempBuf->GetStatus(&bufStat);
			
			if(!(bufStat == DSBSTATUS_PLAYING)){
					tempBuf->Play(
						0,  // Unused.
						0,  // Priority for voice management.
						0); // Flags.);
					break;
			}			
		}		
	}
	
	return true;
}

bool SoundFXdx::setVolume(int vol){
	
	std::map<int,LPDIRECTSOUNDBUFFER8>::iterator it;

	for (it = voices.begin(); it != voices.end(); it++) {
		LPDIRECTSOUNDBUFFER8 tempBuffer = it->second;
		tempBuffer->SetVolume((LONG)vol);
	}
	
	return true;	
}

bool SoundFXdx::stop(){
	return true;
}

}